import { NextRequest, NextResponse } from 'next/server'
import { ServiceRegistry } from '../services/base.service'

// 基础控制器类
export abstract class BaseController {
  protected serviceRegistry: ServiceRegistry

  constructor() {
    this.serviceRegistry = ServiceRegistry.getInstance()
  }

  // 统一的成功响应
  protected success<T>(data: T, message: string = 'Success'): NextResponse {
    return NextResponse.json({
      success: true,
      message,
      data
    })
  }

  // 统一的错误响应
  protected error(
    message: string, 
    status: number = 500, 
    details?: any
  ): NextResponse {
    return NextResponse.json({
      success: false,
      message,
      ...(details && { details })
    }, { status })
  }

  // 验证请求体
  protected validateBody<T>(body: any, schema: (data: any) => T): T {
    try {
      return schema(body)
    } catch (error) {
      throw new Error(`Invalid request body: ${error instanceof Error ? error.message : 'Unknown error'}`)
    }
  }

  // 从请求头获取用户ID
  protected async getUserIdFromRequest(request: NextRequest): Promise<string> {
    console.log('=== getUserIdFromRequest Debug ===')
    
    // 从 Authorization header 获取 token
    const authHeader = request.headers.get('authorization')
    console.log('Authorization header:', authHeader)
    
    const token = authHeader?.replace('Bearer ', '')
    console.log('Extracted token:', token ? `${token.substring(0, 10)}...` : 'null')
    
    if (!token) {
      console.log('No token found in request')
      throw new Error('Authorization token required')
    }

    const userService = this.serviceRegistry.get('user') as any
    if (!userService) {
      console.log('User service not available')
      throw new Error('User service not available')
    }

    console.log('Verifying token...')
    const user = await userService.verifyToken(token)
    console.log('Token verification result:', user ? `User ID: ${user.id}` : 'Invalid')
    
    if (!user) {
      throw new Error('Invalid token')
    }

    return user.id
  }

  // 处理异步操作
  protected async handleAsync<T>(
    operation: () => Promise<T>,
    errorMessage: string = 'Operation failed'
  ): Promise<NextResponse> {
    try {
      const result = await operation()
      return this.success(result)
    } catch (error) {
      console.error(`${errorMessage}:`, error)
      
      const errorMsg = error instanceof Error ? error.message : 'Unknown error'
      
      if (errorMsg.includes('Unauthorized') || errorMsg.includes('token')) {
        return this.error('Unauthorized', 401)
      }
      
      if (errorMsg.includes('Permission denied')) {
        return this.error('Permission denied', 403)
      }
      
      if (errorMsg.includes('not found')) {
        return this.error('Resource not found', 404)
      }
      
      if (errorMsg.includes('already exists')) {
        return this.error('Resource already exists', 409)
      }
      
      return this.error(errorMessage, 500, {
        error: errorMsg
      })
    }
  }

  // 健康检查
  async healthCheck(): Promise<NextResponse> {
    return this.handleAsync(async () => {
      const healthStatus = await this.serviceRegistry.healthCheckAll()
      return {
        status: 'healthy',
        services: healthStatus,
        timestamp: new Date().toISOString()
      }
    }, 'Health check failed')
  }

  // 获取指标
  async getMetrics(): Promise<NextResponse> {
    return this.handleAsync(async () => {
      return this.serviceRegistry.getAllMetrics()
    }, 'Failed to get metrics')
  }
}

// 请求验证装饰器
export function validateRequest<T>(
  schema: (data: any) => T
) {
  return function (target: any, propertyName: string, descriptor: PropertyDescriptor) {
    const method = descriptor.value

    descriptor.value = async function (request: NextRequest, ...args: any[]) {
      try {
        const body = await request.json()
        const validatedData = schema(body)
        
        // 将验证后的数据添加到请求对象
        ;(request as any).validatedBody = validatedData
        
        return await method.call(this, request, ...args)
      } catch (error) {
        return NextResponse.json({
          success: false,
          message: 'Invalid request body',
          details: error instanceof Error ? error.message : 'Unknown error'
        }, { status: 400 })
      }
    }
  }
}

// 认证装饰器
export function requireAuth() {
  return function (target: any, propertyName: string, descriptor: PropertyDescriptor) {
    const method = descriptor.value

    descriptor.value = async function (request: NextRequest, ...args: any[]) {
      try {
        const userId = await (this as any).getUserIdFromRequest(request)
        ;(request as any).userId = userId
        
        return await method.call(this, request, ...args)
      } catch (error) {
        return NextResponse.json({
          success: false,
          message: 'Authentication required',
          details: error instanceof Error ? error.message : 'Unknown error'
        }, { status: 401 })
      }
    }
  }
}

// 权限检查装饰器
export function requirePermission(permission: string) {
  return function (target: any, propertyName: string, descriptor: PropertyDescriptor) {
    const method = descriptor.value

    descriptor.value = async function (request: NextRequest, ...args: any[]) {
      try {
        const userId = (request as any).userId
        if (!userId) {
          throw new Error('User not authenticated')
        }

        // 这里可以添加更复杂的权限检查逻辑
        // 例如检查用户角色、资源权限等
        
        return await method.call(this, request, ...args)
      } catch (error) {
        return NextResponse.json({
          success: false,
          message: 'Permission denied',
          details: error instanceof Error ? error.message : 'Unknown error'
        }, { status: 403 })
      }
    }
  }
}
